<?php

namespace common\components;

use Yii;
use yii\i18n\MissingTranslationEvent;

class TranslationEventHandler
{

    public static function handleMissingTranslation(MissingTranslationEvent $event)
    {
        $messageFile = self::getMessageFilePath($event->category, $event->language);
        $messages = self::loadMessagesFromFile($messageFile, $event);
        if (isset($messages[$event->message])) {
            $message = $messages[$event->message];
        } else {
            $message = $event->message;
        }
        $event->translatedMessage = $message;
    }

    /**
     * Returns message file path for the specified language and category.
     *
     * @param string $category the message category
     * @param string $language the target language
     * @return string path to message file
     */
    protected function getMessageFilePath($category, $language)
    {
        $messageFile = Yii::getAlias('@app/messages') . '/' . $language . '/';
        $translation = Yii::$app->i18n->translations['*'];
        if (isset($translation->fileMap[$category])) {
            $messageFile .= $translation->fileMap[$category];
        } else {
            $messageFile .= str_replace('\\', '/', $category) . '.php';
        }
        return $messageFile;
    }

    /**
     * Loads the message translation for the specified language and category or returns null if file doesn't exist.
     *
     * @param $messageFile
     * @return array|mixed|null
     */
    protected function loadMessagesFromFile($messageFile, $event)
    {
        if (is_file($messageFile)) {
            $messages = include $messageFile;
            if (!is_array($messages)) {
                $messages = [];
            }
        }

        if (strpos($event->category, '@') === 0) {
            $overridesPath = Yii::getAlias(strstr($event->category, '/', true) . '/messages/overrides/');
            $fileName = implode('.', [
                $event->language,
                ltrim(strstr($event->category, '/'), '/'),
                'override.php'
            ]);
        } else {
            $overridesPath = Yii::getAlias('@app/messages/overrides/');
            $fileName = implode('.', [
                $event->language,
                $event->category,
                'override.php'
            ]);
        }

        if (is_file($overridesPath . $fileName)) {
            $overrides = include $overridesPath . $fileName;
            if (!is_array($overrides)) {
                $overrides = [];
            }
        }

        if (isset($messages) && !isset($overrides)) {
            return $messages;
        } elseif (!isset($messages) && isset($overrides)) {
            return $overrides;
        } elseif (isset($messages) && isset($overrides)) {
            return array_merge($messages, $overrides);
        } else {
            return null;
        }
    }

}
